package com.ruiyi.subway.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
	private static final Log log = LogFactory.getLog(GlobalExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		log.error(getLogMessage(request, ex), ex);
		response.setContentType("application/json;charset=UTF-8");
		ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
		mav.addObject("success", false);
		//mav.addObject("message", ex);
		mav.addObject("message", "系统内部错误,请联系管理员");
		return mav;
	}

	private String getLogMessage(HttpServletRequest req, Exception ex) {
		return String.format("%s %s failed, detail: %s" , req.getMethod(), req.getPathInfo(), ex.getMessage());
	}
}
